/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */

#include "WdtFile.h"

namespace PQGame
{
	WdtFile::~WdtFile(void)
	{
	}

	WdtFile::WdtFile(PQEngine::FileBase *f)
		: version(0),mphd(0),wmo_filename_list(0),modf_count(0),modfs(0)
	{
		init(f);
	}

	void WdtFile::init(PQEngine::FileBase *f)
	{
		_file=f;
		if(f==0){
			return;
		}
		
		char fourcc[5];
		int size;

		f->open();
		while (!f->eof()) {
			f->read(fourcc,4);
			f->read(&size, 4);
			flipcc(fourcc);
			fourcc[4] = 0;

			assert(size>=0);//illegal wdt file
			if(strcmp(fourcc,"MVER") == 0){
				if(size>0){
					f->read(&version, 4);
				}
			}else if (strcmp(fourcc,"MPHD") == 0) {
				if(size>0){
					mphd=new wdt_mphd;
					f->read(&mphd->flags, 4);
					f->read(&mphd->sth,4);
					f->read(&mphd->unused,24);
				}
			}else if (strcmp(fourcc,"MAIN") == 0) {
				//Map tile table.
				//contains 64x64 = 4096 records of 8 bytes each.
				//int32 flags;
				//AsyncObject *asyncobject;
				if(size>0){		
					for (int i=0; i<64; i++) {
						for (int j=0; j<64; j++) {
							f->read(&map_tile_flag_table[i][j], 4);
							f->read(&map_tile_async_obj_table[i][j],4);
						}
					}
				}
			}else if (strcmp(fourcc,"MWMO") == 0) {
				//For worlds with no terrain, there is one MWMO and one MODF chunk.
				//otherwise there is no such field
				//filename for WMO (world map objects) that appear in this map. A zero-terminated string.
				// global map objects
				if (size>0) {
					wmo_filename_list=new std::vector<std::string>();
					char *buf = new char[size];
					f->read(buf, size);
					char *p=buf;
					while (p<buf+size) {
						std::string path(p);
						p+=strlen(p)+1;
						wmo_filename_list->push_back(path);
					}
					delete[] buf;
				}
			}else if (strcmp(fourcc,"MODF") == 0) {
				if(size>0){
					//Placement information for the WMO. 64 bytes.
					modf_count=size / 64;
					modfs=new wdt_modf[modf_count];
					for(int i=0;i<modf_count;i++){
						wdt_modf *modf=modfs+i;
						f->read(&modf->nameId,4);
						f->read(&modf->uniqueId,4);
						f->read(modf->pos,12);
						f->read(modf->rot,12);
						f->read(modf->extents,24);
						f->read(&modf->flags,4);
						f->read(&modf->doodad_set,2);
						f->read(&modf->nameSet,2);
					}
				}
			}else{
				f->advance(size);
			}
		}//end of while
		f->close();
	}
}
